package core;

import java.util.Stack;
import ui.View;


import storage.DataManager;
import action.Action;

public class Controller implements Runnable
{
	private Stack<Action> undoStack;
	private UiController ui;
	private String command;
	public Controller() {
		ui = new UiController();
		DataManager.loadLists();
		undoStack = new Stack<Action>();
	}

	public void executeCommand(String command) {
		Log.debug("Cont : entering executeCommand");
		Action actionPerformer = null;
		if (command == null || command.equals("")) {
			return;
		} else if (command.trim().equals("exit")) {
			exit();
		} else if (command.equals("undo") && !undoStack.empty()){
			Action undoAction = undoStack.pop();
			ui.setResult(undoAction.undo());
			ui.showResult(actionPerformer);
		} else {
			actionPerformer = Action.getActionObject(command);
			ui.setResult(actionPerformer.execute(command));
			ui.showResult(actionPerformer);
			if (actionPerformer.isUndoable()) {
				undoStack.push(actionPerformer);	
			}
		}
		if (command.toLowerCase().equals("update")) {
			if (ui.getResult().length == 1) {
				exit();
			}
		}
	}

//	public String partialCommand(String command) {
//		return null;
//	}

	public String[] listNames()
	{
		Log.debug("cont: entering listName");
		return DataManager.getListNames();
	}

	public String[] getEventsInList(String listName) {
		Log.debug("cont: entering getEventsInList");
		return DataManager.getEventsInList(listName);
	}

	public void setView(View view) {
		Log.debug("cont: entering setView");
		this.ui.setView(view);
	}

	public void setCommand(String command) {
		Log.debug("cont: entering setCommand");
		this.command = command;
	}
	
	@Override
	public void run() {
		Log.debug("cont: entering run");
		executeCommand(command);
	}
	public void exit() {
		Log.debug("cont: entering exit");
		ui.getView().unregisterProvider();
	}

	public String getCommand() {
		Log.debug("cont: entering getCommand");
		return command;
	}
}
